/*
 * Copyright 2004 original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jbfilter.jsp;

import java.util.EnumSet;
import java.util.Iterator;

import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.jstl.core.LoopTagSupport;


public class ForEachEnumTag extends LoopTagSupport {

	private static final long serialVersionUID = 1L;
	
	@SuppressWarnings("rawtypes")
	private Class<Enum> enumClass;
	@SuppressWarnings("rawtypes")
	private Iterator<Enum> iterator;
	
	private static final String ERR_MESS = new StringBuilder()
		.append(JbfilterTagAttribute.enumClass)
		.append(" in ")
		.append(JbfilterTag.forEachEnum)
		.append("takes a fully qualified Enum class string or an Enum class Class<Enum>.")
		.toString();
	
	@Override
	protected boolean hasNext() throws JspTagException {
		if (iterator == null) {
			return false;
		} else {
			return iterator.hasNext();
		}
	}

	@Override
	protected Object next() throws JspTagException {
		return iterator.next();
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void prepare() throws JspTagException {
		if (enumClass != null) {
			iterator = EnumSet.allOf(enumClass).iterator();	
		}
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void setEnumClass(Object classForName) throws ClassNotFoundException {
		if (classForName instanceof String) {
			enumClass = (Class<Enum>)Class.forName((String)classForName);	
		} else if (classForName instanceof Class) {
			if (enumClass.getSuperclass() != Enum.class) {
				throw new ClassCastException(ERR_MESS);
			}
			enumClass = (Class<Enum>) classForName;
		} else {
			throw new ClassCastException(ERR_MESS);
		}
	}
	
	public void setBegin(int begin) {
		this.begin = begin;
		beginSpecified = true;
	}

	public void setEnd(int end) {
		this.end = end;
		endSpecified = true;
	}

	public void setStep(int step) {
		this.step = step;
		stepSpecified = true;
	}

}
